package com.cashbook.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.cashbook.pojo.TbUser;
import com.cashbook.service.UserService;

import entity.PageResult;
import entity.Result;
import net.sf.json.JSONObject;
import utils.AesCbcUtil;
import utils.HttpRequest;
/**
 * controller
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	
	
	/**
	 * 返回全部列表
	 * @return
	 */
	@RequestMapping("/findAll")
	public List<TbUser> findAll(){			
		return userService.findAll();
	}
	
	/**
	 * 返回全部列表
	 * @return
	 */
	@RequestMapping("/findPage")
	public PageResult  findPage(int page,int rows){			
		return userService.findPage(page, rows);
	}
	
	/**
	 * 增加
	 * @param admin
	 * @return
	 */
	@RequestMapping("/add")
	public Result add(@RequestBody TbUser user){
		try {
			userService.add(user);
			return new Result(true, "增加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "增加失败");
		}
	}
	
	/**
	 * 修改
	 * @param admin
	 * @return
	 */
	@RequestMapping("/update")
	public Result update(@RequestBody TbUser user){
		try {
			userService.update(user);
			return new Result(true, "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "修改失败");
		}
	}	
	
	/**
	 * 获取实体
	 * @param id
	 * @return
	 */
	@RequestMapping("/findOne")
	public TbUser findOne(Long id){
		return userService.findOne(id);		
	}
	
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	public Result delete(Long [] ids){
		try {
			userService.delete(ids);
			return new Result(true, "删除成功"); 
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "删除失败");
		}
	}
	
		/**
	 * 查询+分页
	 * @param brand
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/search")
	public PageResult search(@RequestBody TbUser user, int page, int rows  ){
		return userService.findPage(user, page, rows);		
	}
	
	/**
	 * 按照昵称和性别搜索
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/criteria")
	public List<TbUser> search02(HttpServletRequest request,HttpServletResponse response  ){
		 Long   gender=null;
		 try{
			 gender =Long.parseLong(request.getParameter("gender"));
	     }catch(Exception e){
	     }
		String nickName=request.getParameter("nickName");
		
		return userService.findByNickName(nickName,gender);		
	}
	/**
	 * 通过openId查找用户信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("findByOpenId")
	public List<TbUser> findByOpenId(HttpServletRequest request,HttpServletResponse response){
		String openId =request.getParameter("openId");
		return userService.findByOpenId(openId);
		
	}
	@ResponseBody
	@RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET)
	public Map decodeUserInfo(String encryptedData, String iv, String code) {

	    Map map = new HashMap();
	    //登录凭证不能为空
	    if (code == null || code.length() == 0) {
	        map.put("status", 0);
	        map.put("msg", "code 不能为空");
	        return map;
	    }

	    //小程序唯一标识   (在微信小程序管理后台获取)
	    String wxspAppid = "wxca14a4e5cbdfe8f1";
	    //小程序的 app secret (在微信小程序管理后台获取)
	    String wxspSecret = "ceb13ebede7e4c527bcd049f26ab1010";
	    //授权（必填）
	    String grant_type = "authorization_code";


	    //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
	    //请求参数
	    String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
	    //发送请求
	    String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
	    //解析相应内容（转换成json对象）
	    JSONObject json = JSONObject.fromObject(sr);
	    //获取会话密钥（session_key）
	    String session_key = json.get("session_key").toString();
	    //用户的唯一标识（openid）
	    String openid = (String) json.get("openid");

	    //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
	    try {
	        String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
	        if (null != result && result.length() > 0) {
	            map.put("status", 1);
	            map.put("msg", "解密成功");

	            JSONObject userInfoJSON = JSONObject.fromObject(result);
	            Map userInfo = new HashMap();
	            userInfo.put("openId", userInfoJSON.get("openId"));
	            userInfo.put("nickName", userInfoJSON.get("nickName"));
	            userInfo.put("gender", userInfoJSON.get("gender"));
	            userInfo.put("city", userInfoJSON.get("city"));
	            userInfo.put("province", userInfoJSON.get("province"));
	            userInfo.put("country", userInfoJSON.get("country"));
	            userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
	            userInfo.put("unionId", userInfoJSON.get("unionId"));
	            map.put("userInfo", userInfo);
	            return map;
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    map.put("status", 0);
	    map.put("msg", "解密失败");
	    return map;
	}
	
	
}
